import 'dart:convert';

import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StorageService extends GetxService {
  static StorageService get to => Get.find();
  late final SharedPreferences _prefs;

  Future<StorageService> init() async {
    _prefs = await SharedPreferences.getInstance();
    return this;
  }

  // ===================== 设置 获取 数据 =====================
  Future<bool> setInt(String key, int value) {
    return _prefs.setInt(key, value);
  }

  int getInt(String key, {int defaultValue = 0}) {
    return _prefs.getInt(key) ?? defaultValue;
  }

  Future<bool> setDouble(String key, double value) {
    return _prefs.setDouble(key, value);
  }

  double getDouble(String key, {double defaultValue = 0.0}) {
    return _prefs.getDouble(key) ?? defaultValue;
  }

  Future<bool> setString(String key, String value) {
    return _prefs.setString(key, value);
  }

  String getString(String key, {String defaultValue = ""}) {
    return _prefs.getString(key) ?? defaultValue;
  }

  Future<bool> setBool(String key, bool value) {
    return _prefs.setBool(key, value);
  }

  bool getBool(String key, {bool defaultValue = false}) {
    return _prefs.getBool(key) ?? defaultValue;
  }

  Future<bool> setStringList(String key, List<String> value) {
    return _prefs.setStringList(key, value);
  }

  List<String> getStringList(String key, {List<String> defaultValue = const []}) {
    return _prefs.getStringList(key) ?? defaultValue;
  }

  /// 根据key存储Map类型
  Future<bool> setMap(String key, Map value) {
    return _prefs.setString(key, json.encode(value));
  }

  /// 根据key获取Map类型
  Map getMap(String key) {
    String jsonStr = _prefs.getString(key) ?? "";
    return jsonStr.isEmpty ? Map : json.decode(jsonStr);
  }

  // ===================== 设置 获取 数据 =====================

  /// 获取持久化数据中所有存入的key
  Set<String> getKeys() {
    return _prefs.getKeys();
  }

  /// 获取持久化数据中是否包含某个key
  bool containsKey(String key) {
    return _prefs.containsKey(key);
  }

  /// 删除持久化数据中某个key
  Future<bool> remove(String key) async {
    return await _prefs.remove(key);
  }

  /// 清除所有持久化数据
  Future<bool> clear() async {
    return await _prefs.clear();
  }

  /// 重新加载所有数据,仅重载运行时
  Future<void> reload() async {
    return await _prefs.reload();
  }
}
